package com.yangguang.huahui.mvp.model;

import com.yangguang.huahui.api.ImageApi;
import com.yangguang.huahui.entity.Upload;
import com.yangguang.huahui.net.NetManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Observable;

/**
 * Created by Administrator on 2017/3/8.
 */

public class UploadModel {
    public Observable<ResponseBody> uploadFile(List<String> pathList){
        ImageApi imageApi = NetManager.getInstance().create(ImageApi.class);
        return imageApi.uploads(upLoads(pathList));
    }

    public Observable<ResponseBody> uploadFile(File file){
        ImageApi imageApi = NetManager.getInstance().create(ImageApi.class);
        return imageApi.uploads(upLoad(file));
    }

    /**
     * 上传图片(多图)
     * create by weiang at 2016/5/20 17:33.
     */
    private List<MultipartBody.Part> upLoads(List<String> pathList) {//此处是伪代码，获取多张待上传图片的地址列表
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型
        //多张图片
        for (int i = 0; i < pathList.size(); i++) {
            File file = new File(pathList.get(i));//filePath 图片地址
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("file[]", file.getName(), imageBody);//"imgfile"+i 后台接收图片流的参数名
        }
        return builder.build().parts();
    }

    /**
     * 上传图片（单图）
     * create by weiang at 2016/5/20 17:33.
     */
    private List<MultipartBody.Part> upLoad(File file) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("file[]", file.getName(), imageBody);//file 后台接收图片流的参数名
        return  builder.build().parts();
    }
}
